package YAVMM::Server;
use warnings;
use strict;

use Dancer ':syntax';
set serializer => 'JSON';

use Template;

use YAVMM::Server::Utils;
use YAVMM::Server::Auth;

our $VERSION = '0.1';

my %template_globals = (
    'get_clusters' => \&YAVMM::Server::Utils::get_clusters,
    'get_hosts'    => \&YAVMM::Server::Utils::get_hosts,
    'title'        => 'YAVMM',
    'uri_for'      => \&uri_for,
);

before sub {
    # Beware side effects
    # Initialize var settings and hostdb.
    YAVMM::Server::Utils::get_settings;
    YAVMM::Server::Utils::get_hostdb;

    my $name = `hostname`;
    chomp $name;
    var name => $name;
};

before sub {

    session timestamp => time();
    session address   => request->address;

    session lastpage => request->path_info;

    if (not session('user')) {

	if (request->path_info !~ m|\A /login |x) {
	    # If we're dealing with a JSON RPC request,
	    # just error out with a 403.
	    if (request->path_info =~ m|\A /json/|x) {
		return send_error("Permission denied", 403);
	    }
	    # Otherwise, send the user to a log in page.
	    else {
		var requested_path => request->path_info;
		request->path_info('/login');
	    }
	}
    }
    # TODO: check for session timeout
};

get '/' => sub {
    template 'index', {
	%template_globals,
	'title'   => 'Welcome',
    };
};

# show cluster details
get '/cluster/:cluster_name' => sub {
    template 'cluster', {
	%template_globals,
	'title'        => "Cluster: ".params->{cluster_name},
	'cluster_name' => params->{cluster_name}
    };
};

# show host details
get '/host/:host_name' => sub {
};

# show single guest
get '/guest/:guest_name' => sub {
};

# /guest/:guest_name/console
# /guest/:guest_name/commands

# show guest database
get '/guests' => sub {
    template 'guests', {
	%template_globals,
	'title'   => 'Guests',
    };
};

# /guests/add
# /guests/edit/:name
# /guests/edit/:name/disks
# /guests/edit/:name/usbdevices
# /guests/edit/:name/nics
# /guests/edit/:name/console

get '/login' => sub {
    template 'login', {
	'title'   => 'Log in',
	'no_menu' => 1,
    };
};

post '/login' => sub {
    my $login_successful = 0;

    ## Check credenials
    my $user = params->{user};
    my $pass = params->{pass};

    debug 'vars->{settings} is: ', ref vars->{settings};

    my $auth = YAVMM::Server::Auth->new(settings => vars->{settings});
    $auth->load_plugin(config->{'auth plugin'});

    $login_successful = $auth->authenticate($user, $pass);

    if ($login_successful) {
	session user => $user;
	redirect params->{path} || '/';
    }
    else {
	redirect '/login?failed=1';
    }
};

get '/logout' => sub {
    session->destroy;
    redirect '/login';
};

true;
